package com.zjw.forum.controller;

import com.sun.istack.internal.NotNull;
import com.zjw.forum.common.AppResult;
import com.zjw.forum.common.ResultCode;
import com.zjw.forum.dao.ArticleMapper;
import com.zjw.forum.dao.BoardMapper;
import com.zjw.forum.model.Article;
import com.zjw.forum.model.Board;
import com.zjw.forum.model.User;
import com.zjw.forum.services.IArticleService;
import com.zjw.forum.services.IUserService;
import com.zjw.forum.utils.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Api("文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private BoardMapper boardMapper;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IUserService userService;
    //作者id从令牌中取
    @PostMapping("/create")
    public AppResult postArticle(HttpServletRequest request,
                                 @RequestParam("title") @NotNull @ApiParam("文章标题") String title,
                                 @RequestParam("content") @NotNull @ApiParam("文章内容")String content,
                                 @RequestParam("boardId") @NotNull @ApiParam("板块Id")Long boardId){
        //获取作者id
        String user_token = request.getHeader("user_token");
        User user = JWTUtil.getUserFromToken(user_token);
        if(user==null){
            //令牌不合法
            log.error(ResultCode.FAILED_TOKEN.getMessage());
            return AppResult.failed(ResultCode.FAILED_TOKEN);
        }
        //判断该用户是否被禁言了，禁言就无法发布文章
        if(user.getState()==1){
            log.error(ResultCode.FAILED_USER_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //对传入的板块Id进行校验 （板块对象如果禁用状态或者被删除状态就返回错误日志）
        Board board = boardMapper.selectByPrimaryKey(boardId);
        if(board==null||board.getState()==1||board.getDeleteState()==1){
            log.error(ResultCode.FAILED_BOARD_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //构造article对象
        Article article=new Article();
        article.setContent(content);
        article.setTitle(title);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        articleService.postArticle(article);
        return AppResult.success("发帖成功");
    }

    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId",required = false) @ApiParam("板块id") Long boardId){
        //如果是首页的话不需要boardId,显示所有文章
        if(boardId==null){
            return AppResult.success(articleMapper.selectAll());
        }
        //校验板块是否禁用或者删除了
        //对传入的板块Id进行校验 （板块对象如果禁用状态或者被删除状态就返回错误日志）
        Board board = boardMapper.selectByPrimaryKey(boardId);
        if(board==null||board.getState()==1||board.getDeleteState()==1){
            log.error(ResultCode.FAILED_BOARD_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //获取文章
        List<Article> articles = articleService.selectAllByBoardId(boardId);
        return AppResult.success(articles);
    }
    @ApiOperation("查询帖子详情")
    @GetMapping("/details")
    public AppResult getDetail(HttpServletRequest httpServletRequest,
            @NotNull @ApiParam("帖子id") @RequestParam(value="id") Long id){
        if(id<=0){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        Article article = articleService.selectDetailById(id);
        if(article==null){
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS .getMessage());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断令牌中的用户
        String user_token = httpServletRequest.getHeader("user_token");
        User userFromToken = JWTUtil.getUserFromToken(user_token);
        if(userFromToken==null){
            //令牌不合法
            log.error(ResultCode.FAILED_TOKEN.getMessage());
            return AppResult.failed(ResultCode.FAILED_TOKEN);
        }
        if(userFromToken.getId().equals(article.getUser().getId())){
            article.setIsOwn(true);
        }
        System.out.println(article);
        return AppResult.success(article);
    }
    @ApiOperation("编辑文章")
    @PostMapping("/modify")
    public AppResult editorArticle(HttpServletRequest httpServletRequest,
                                   @NotNull @ApiParam("文章id") @RequestParam("id") Long id,
                                   @NotNull @ApiParam("文章标题") @RequestParam("title")String title,
                                   @NotNull @ApiParam("文章内容") @RequestParam("content")String content){
        //更新之前进行校验身份
        String user_token = httpServletRequest.getHeader("user_token");
        User userFromToken = JWTUtil.getUserFromToken(user_token);
        if(userFromToken==null){
            log.error(ResultCode.FAILED_TOKEN.getMessage());
            return AppResult.failed(ResultCode.FAILED_TOKEN);
        }
        //查出文章作者信息
        Article article1 = articleService.selectArticle(id);
        //与登陆用户判断
        if(!article1.getUserId().equals(userFromToken.getId())){
            //不是同一个用户
            log.error(ResultCode.FAILED_USER_NOT_OWN.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_OWN);
        }
        //校验当前用户/作者是否被禁言
        if(userFromToken.getState()==1){
            log.error(ResultCode.FAILED_USER_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验文章是否被禁言
        if(article1.getState()==1){
            log.error(ResultCode.FAILED_ARTICLE_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //开始更新
        int i = articleService.updateArticleById(id, title, content);
        if(i!=1){
            //更新失败
            log.warn(ResultCode.FAILED.getMessage());
            return AppResult.failed(ResultCode.FAILED);
        }
        return AppResult.success("编辑成功");
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUpArticle(
            HttpServletRequest httpServletRequest,
            @NotNull @ApiParam("文章id") @RequestParam("id") Long id){
        String user_token = httpServletRequest.getHeader("user_token");
        User userFromToken = JWTUtil.getUserFromToken(user_token);
        if(userFromToken==null){
            log.error(ResultCode.FAILED_TOKEN.getMessage());
            return AppResult.failed(ResultCode.FAILED_TOKEN);
        }
        //校验登陆用户是否被禁言了
        if(userFromToken.getState()==1){
            log.error(ResultCode.FAILED_USER_BANNED.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        int i = articleService.updateLikeCount(id);
        if(i!=1){
            log.warn(ResultCode.FAILED.getMessage());
            return AppResult.failed(ResultCode.FAILED);
        }
        return AppResult.success("点赞成功");
    }

    @ApiOperation("删除")
    @PostMapping("/delete")
    public AppResult deleteArticle(
            HttpServletRequest httpServletRequest,
            @NotNull @ApiParam("文章id") @RequestParam("id") Long id){
        String user_token = httpServletRequest.getHeader("user_token");
        User userFromToken = JWTUtil.getUserFromToken(user_token);
        if(userFromToken==null){
            log.error(ResultCode.FAILED_TOKEN.getMessage());
            return AppResult.failed(ResultCode.FAILED_TOKEN);
        }
        Article article = articleService.selectArticle(id);
        //判断删除人与作者是否同一个
        if(!article.getUserId().equals(userFromToken.getId())){
            log.error(ResultCode.FAILED_USER_NOT_OWN.getMessage());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_OWN);
        }
        articleService.deleteAritcle(id);
        return AppResult.success("删除成功");
    }

    @ApiOperation("显示用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult getAllByUserId(
            HttpServletRequest request,
            @NotNull @ApiParam("用户id") @RequestParam(value="userId",required = false)Long userId){
        List<Article> articles;
        //登陆用户
        if(userId==null){
            String user_token = request.getHeader("user_token");
            User user = JWTUtil.getUserFromToken(user_token);
            if(user==null){
                //令牌不合法
                log.error(ResultCode.FAILED_TOKEN.getMessage());
                return AppResult.failed(ResultCode.FAILED_TOKEN);
            }
            //根据userId，获取帖子列表 可能为空
            articles = articleService.selectAllByUserId(user.getId());
        }else{
            //其他用户
            User user = userService.getUserinfo(userId);
            //判断user
            if(user==null){
                log.warn(ResultCode.ERROR_SERVICES.getMessage());
                return AppResult.failed(ResultCode.ERROR_SERVICES);
            }
            articles = articleService.selectAllByUserId(userId);
        }
        return AppResult.success(articles);
    }
}
